package main

import (
	"errors"
	"fmt"
	"sync"
	"time"
)

var TimeTickMap11 sync.Map

// 延时操作
func Tick(duration time.Duration) (IsTimeOver bool, err error) {
	//todo 计时
	timer := time.NewTimer(duration)
	TimeTickMap11.Store("t.ProjectId", make(chan struct{}))
	defer timer.Stop()
	for {
		stopTick, ok := TimeTickMap11.Load("t.ProjectId")
		if !ok {
			return false, errors.New("计时器异常退出")
		}
		select {
		case <-timer.C:
			fmt.Println("Time out!")
			TimeTickMap11.Delete("t.ProjectId")
			return true, nil
		case cc := <-stopTick.(chan struct{}):
			fmt.Println(cc)
			TimeTickMap11.Delete("t.ProjectId")
			return false, nil
		}
	}
}

func TickForEvery(duration time.Duration, f func()) (IsTimeOver bool, err error) {
	timer := time.NewTimer(duration)
	TimeTickMap11.Store("t.ProjectId", make(chan struct{}))
	ticker := time.NewTicker(time.Second * 1) //定义一个1秒间隔的定时器
	defer ticker.Stop()
	defer timer.Stop()
	for {
		stopTick, ok := TimeTickMap11.Load("t.ProjectId")
		if !ok {
			return false, errors.New("计时器异常退出")
		}
		select {
		case <-timer.C:
			TimeTickMap11.Delete("t.ProjectId")
			return true, nil
		case <-ticker.C:
			f()
		case <-stopTick.(chan struct{}):
			TimeTickMap11.Delete("t.ProjectId")
			return false, nil
		}
	}
}

func main() {
	go func() {
		time.Sleep(time.Second * 2)
		stopTick, ok := TimeTickMap11.Load("t.ProjectId")
		if ok {
			stopTick.(chan struct{}) <- struct{}{}
		}
	}()
	over, err := TickForEvery(time.Second*5, TTL)
	if err == nil {
		if over == true {
			fmt.Println("is time over")
		} else {
			fmt.Println("is stop")
		}
	}
}

func TTL() {
	fmt.Println("do do")
}
